﻿using CommandService;
using Entity;
using Entity.DbEntity;
using Entity.FrameEntity;
using Entity.ViewEntity.barPrint.ToClient;
using log4net;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using SysFramework;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Tools;

namespace BLL
{
    public class WareHouseBLL : PubMethod
    {
        Commands cmd;
        OutBaseHelper outBase;
        ReturnResult rsl;
        SystemManagement sysBLL;
        List<OperateModel> operList;
        ILog _log;
        public WareHouseBLL()
        {
            //数据交互
            cmd = new Commands();
            outBase = new OutBaseHelper();
            sysBLL = new SystemManagement();
            _log = LogManager.GetLogger(this.GetType().Name);
        }

        #region 列表获取

        /// <summary>
        /// 仓库列表信息获取方法
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="pageCount"></param>
        /// <param name="condition"></param>
        /// <returns></returns>
        public ReturnResult getWareHouseList(string pageIndex, string pageSize, ref string pageCount, string condition,string baseCode)
        {
            rsl = new ReturnResult();
            try
            {
                StringBuilder sb = new StringBuilder();
                sb.Append(" isdel=0 and baseCode='" + baseCode + "' ");
                sb = CreateSelectCondition(sb, condition);
                var list = cmd.PageList("fun_WareHouse_Info", pageIndex, pageSize, sb.ToString(), "id desc", ref pageCount);
                var tempList = JsonConvert.DeserializeObject<List<Dictionary<string, string>>>(JsonConvert.SerializeObject(list));
                if (tempList.Count > 0)
                {
                    foreach (var item in tempList)
                    {
                        if (item["status"].ToString().Equals("open"))
                        {
                            item["statusName"] = "启用";
                        }
                        else
                        {
                            item["statusName"] = "停用";
                        }
                        if (item["isSync"].ToString().Equals("Y"))
                        {
                            item["isSyncName"] = "是";
                        }
                        else
                        {
                            item["isSyncName"] = "否";
                        }
                    }
                }
                rsl.Data = tempList;
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        /// <summary>
        /// 仓库货位列表信息
        /// </summary>
        /// <param name="wareCode">仓库编码</param>
        /// <returns></returns>
        public ReturnResult WarePositionList(string baseCode, string wareCode)
        {
            rsl = new ReturnResult();
            try
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("select * from fun_CommonData_Info where cType='WP' and isDel='0' and ");
                sb.Append("specFile='" + baseCode + "'");
                sb.Append(" and parentCode='" + wareCode + "' ");

                var table = cmd.GetDataTable(sb.ToString());
                var list = cmd.TableToDictionary(table);
                var tempList = JsonConvert.DeserializeObject<List<Dictionary<string, string>>>(JsonConvert.SerializeObject(list));
                if (tempList.Count > 0)
                {
                    foreach (var item in tempList)
                    {
                        if (item["status"].ToString().Equals("Y"))
                        {
                            item["statusName"] = "启用";
                        }
                        else
                        {
                            item["statusName"] = "停用";
                        }
                    }
                }
                rsl.Data = tempList;
                // rsl.Data=list;
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        #endregion

        #region 仓库、货位同步 （U8）

        /// <summary>
        /// 仓库数据同步
        /// </summary>
        /// <param name="userCode"></param>
        /// <param name="baseCode"></param>
        /// <param name="isAuto"></param>
        /// <returns></returns>
        public ReturnResult SyncWareHouse(string userCode, string baseCode, bool isAuto = false)
        {
            rsl = new ReturnResult();
            try
            {
                List<OperateModel> list = new List<OperateModel>();
                OperateModel oper;
                string sql = "select cWhCode,cWhName,dWhEndDate  from Warehouse ";
                var wTable =  outBase.getData(sql, baseCode);//获取全部U8仓库信息
                sql = "select * from fun_WareHouse_Info where baseCode = '" + baseCode + "'";
                var qTable = cmd.GetDataTable(sql);//获取系统所有的仓库数据信息
                foreach (DataRow r in wTable.Rows)
                {
                    oper = new OperateModel();
                    DbWareHouse ware = new DbWareHouse();
                    ware.baseCode = baseCode;
                    ware.houseCode = r["cWhCode"].ToString();
                    ware.houseName = r["cWhName"].ToString();
                    ware.isSync = "Y";
                    //判断仓库是否启用（停用日期是否为空）
                    if (string.IsNullOrWhiteSpace(r["dWhEndDate"].ToString()))
                    {
                        ware.status = "open";
                    }
                    else
                    {
                        ware.status = "close";
                    }
                    ware.isDel = 0;
                    var dr = qTable.Select("houseCode='" + r["cWhCode"].ToString() + "'");
                    if (dr.Length > 0)
                    {
                        oper.Types = OperateModel.OperateType.Edit;
                        oper.Conditions = "houseCode,baseCode";
                    }
                    else
                    {
                        #region 添加操作
                        ware.createuser = userCode;
                        ware.createtime = getNow();
                        oper.Types = OperateModel.OperateType.Add;
                        #endregion
                    }
                    oper.Data = ware;
                    list.Add(oper);
                }
                string msg = "";
                if (list.Count > 0)
                {
                
                    sysBLL.SubmitSyncData(list, "仓库同步", ref msg);
                    if (string.IsNullOrWhiteSpace(msg))
                    {
                        rsl.Result = true;
                    }
                    else
                    {
                        rsl.Result = false;
                        rsl.Message = msg;
                    }
                }
                if (rsl.Result)
                {
                    rsl.Message = "仓库同步完成";
                    return rsl;
                    //var rsl_hw = SyncWarehousePosition(userCode,baseCode, true);//货位信息同步
                    //rsl.Result = true;
                    //if (rsl_hw.Result)
                    //{
                    //    rsl.Message = "数据同步完成";
                    //    return rsl;
                    //}
                    //else
                    //{
                    //    rsl.Message = "仓库同步成功，货位同步失败";
                    //    return rsl;
                    //}
                }
                else
                {
                    rsl.Message = "仓库信息同步失败";
                }
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        
        /// <summary>
        /// 仓库货位数据同步
        /// </summary>
        /// <param name="isAuto"></param>
        /// <returns></returns>
        public ReturnResult SyncWarehousePosition(string userCode, string baseCode, bool isAuto = false)
        {
            rsl = new ReturnResult();
            try
            {
                List<OperateModel> list = new List<OperateModel>();
                OperateModel oper;
                string sql = "select cPosCode,cPosName,cWhCode,bPosEnd from Position";
                var wTable = outBase.getData(sql, baseCode);//获取全部U8仓库货位信息
                sql = "select id,cCode,cName,parentCode,specFile from fun_CommonData_Info where cType='WP'";
                var qTable = cmd.GetDataTable(sql);//获取系统所有仓库数据信息
                foreach (DataRow r in wTable.Rows)
                {
                    oper = new OperateModel();
                    DbCommonData position = new DbCommonData();
                    position.specFile = baseCode;
                    position.cCode = r["cPosCode"].ToString();
                    position.cName = r["cPosName"].ToString();
                    position.parentCode = r["cWhCode"].ToString();
                    string isChild = "0";
                    if (bool.Parse(r["bPosEnd"].ToString()))
                    {
                        isChild = "1";//是否是末级
                    }
                    position.cValues = isChild;//是否是末级
                    position.cType = "WP";
                    position.status = "Y";
                    position.cMemo = "仓库货位";
                    position.isDel = 0;
                    var dr = qTable.Select("cCode='" + r["cPosCode"].ToString() + "' and specFile='" + baseCode + "'");
                    if (dr.Length > 0)
                    {
                        oper.Types = OperateModel.OperateType.Edit;
                        position.id = int.Parse(dr[0]["id"].ToString());
                        oper.Conditions = "id";
                    }
                    else
                    {
                        #region 添加操作
                        position.createuser = userCode;
                        position.createtime = getNow();
                        oper.Types = OperateModel.OperateType.Add;
                        #endregion
                    }
                    oper.Data = position;
                    list.Add(oper);
                }
                if (list.Count > 0)
                {
                    string msg = "";
                    sysBLL.SubmitSyncData(list, "货位同步", ref msg);
                    if (string.IsNullOrWhiteSpace(msg))
                    {
                        rsl.Result = true;
                    }
                    else
                    {
                        rsl.Result = false;
                        rsl.Message = msg;
                    }
                }
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }

        #endregion
        /// <summary>
        /// 获取仓库列表
        /// </summary>
        /// <param name="json"></param>
        /// <returns></returns>
        public List<ItemSelector> GetWarehouseList(string json)
        {
            var list = new List<ItemSelector>();

            try
            {
                var queryDic = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);
                var baseCode = queryDic["baseCode"];

                var sql = $@"SELECT houseCode as code,houseName as name FROM fun_WareHouse_Info 
WHERE [status] = 'open' AND isDel = 0 AND baseCode = '{baseCode}'; ";
                var dt = cmd.GetDataTable(sql);

                list = cmd.TableTolist<ItemSelector>(dt);

            }
            catch (Exception ex)
            {
                _log.Error(ex.Message);
            }

            return list;
        }

    }
}
